from google.appengine.ext import db
from datetime import date, datetime, timedelta
from horseanalysis.model.probability_sets.probability_result_base import ProbabilityResultBase
from horseanalysis.model.win_place import WinPlace

class PlaceProbabilityResult(ProbabilityResultBase):
  horse_no = db.IntegerProperty()
  
  def update_gain_offset(self, results):
    if results.__contains__(str(self.horse_no)):
      self.gain_offset = self.odds
    else:
      self.gain_offset = 0.0
      
    self.put()
  
  @classmethod
  def cal_place_prob(cls, race_batch):
    winning_probability = cls.cal_win_prob(race_batch)
    available_horse_no = []
    place_prob_combination = {}

    for horse_no in winning_probability:
      available_horse_no.append(horse_no)

    for i in available_horse_no:
      for j in available_horse_no:
        for k in available_horse_no:
          if i != j and i != k and j != k:
            prob = cls.cal_individual_place_prob(winning_probability, i, j, k)
            for key in [i, j, k]:
              if not place_prob_combination.has_key(key):
                place_prob_combination[key] = 0
              place_prob_combination[key] += prob

    return place_prob_combination
  
  @classmethod
  def __analyze_batch__(cls, race_batch):
    probability = cls.cal_place_prob(race_batch)
    place_odds = WinPlace.get_place_odds(race_batch)
    
    for horse_no in probability:
      cls.create_new_result(race_batch, horse_no, place_odds[horse_no], probability[horse_no], place_odds[horse_no] * probability[horse_no])
  
  @classmethod
  def create_new_result(cls, race_batch, horse_no, odds, probability, expected_return):
    scheme = cls(race_batch=race_batch, odds=odds, horse_no=horse_no, probability=probability, expected_return=expected_return)
    scheme.put()
  
  @classmethod
  def complete_related_race_batch_probability_result(cls, race_batch):
    race_batch.set_completed_place_probability_set(True)
    
  @classmethod
  def incomplete_related_race_batch_probability_result(cls, race_batch):
    race_batch.set_completed_place_probability_set(False)
    